<?php
namespace Mobile\Controller;
use Think\Controller;
use Org\Util\CryptAES;
use Think\Log;

class MobileController extends Controller {
    
    
    protected $uid = 0;  //用户ID
    protected $channel = ''; //渠道
    
    /* 空操作，用于输出404页面 */
    public function _empty(){
        $this->err('无效的指令调用！');
    }

    
    protected function _initialize(){
        if(IS_POST){
            $this->check_post();
        }else{
            //session('usertoken',null);
            //$this->err('请使用正确的方式递交数据！');
            $str = CONTROLLER_NAME . '/' . ACTION_NAME .',';
            $usertoken = session('usertoken');
            if(!empty($usertoken)){
                $str .= $usertoken;
            }
            //首先根据APP_KEY 解密
            $aes = new CryptAES();
            $aes->set_key(C('APP_KEY'));
            $aes->require_pkcs5();
            $encText = $aes->encrypt($str);
            $this->assign('token',$encText);
            $this->display();
            exit();
        }        
    }
    
    protected function check_login(){
        if(empty($this->uid)){
            $this->err('请先登录后再调用！');
        }
        return $this->uid;
    }
    
    /**
    * 检查token是否正确
    * 
    */
    protected function check_post(){
        $token = I('post.token');
        
        if(empty($token)){
            $this->err('token值没有递交！');
        }
        
        Log::record($token);
        
        //首先根据APP_KEY 解密
        $aes = new CryptAES();
        $aes->set_key(C('APP_KEY'));
        $aes->require_pkcs5();
        $decString = $aes->decrypt($token);
        if(empty($decString)){
            $this->err('无效的token值！');
        }
        
        $arr = explode(',',$decString); //加密字串为 CONTROLLER_NAME/ACTION_NAME . '服务器发回的usertoken'
        if(count($arr)>1){ //表示有usertoken
            $method = CONTROLLER_NAME . '/' . ACTION_NAME;
            if($arr[0]==$method){
                if(!empty($arr[1])){
                    $ret = $this->decrypt_usertoken($arr[1]);
                    if($ret){
                        /* 暂时不用判断是否过期
                        if(NOW_TIME>$ret['expire']){
                            $this->err('usertoken已失效！');
                        } */
                        $this->uid = $ret['uid'];
                        return;
                    }
                }else{
                    $this->uid = session('uid');
                    return;
                }
            }
        }
        $this->err('无效的token值！');
    }
    
    /**
    * 解密用户TOKEN
    * 
    * @param mixed $usertoken
    */
    protected function decrypt_usertoken($usertoken){
        $aes_server = new CryptAES();
        $aes_server->set_key(C('CRYPT_KEY'));
        $aes_server->require_pkcs5();
        $decode = $aes_server->decrypt($usertoken);
        if(empty($decode)) return false;
        $arr = explode(',',$decode);
        if(count($arr)>1){
            return array(
                'uid'=>$arr[0],
                'expire'=>$arr[1],
                'channel'=>$arr[2],
            );
        }else{
            return null;
        }
    }
    
    /**
    * 加密生成usertoken
    * 
    * @param mixed $uid 用户id
    * @param mixed $expire_time 过期时间
    */
    protected function encrypt_usertoken($uid,$expire_time,$channel=''){
        $aes_server = new CryptAES();
        $aes_server->set_key(C('CRYPT_KEY'));
        $aes_server->require_pkcs5();
        $str = "$uid,$expire_time,$channel";
        $decode = $aes_server->encrypt($str);
        return $decode;
    }
    
    /**
    * 解密字符串
    * 
    * @param mixed $token
    */
    protected function decrypt($token){
        $aes = new CryptAES();
        $aes->set_key(C('APP_KEY'));
        $aes->require_pkcs5();
        $decString = $aes->decrypt($token);
        return $decString;
    }
    
    protected function succ($info){
        $this->success($info,'',true);
    }
    
    protected function err($info){
        $this->error($info,'',true);
    }
    
    protected function success($message='',$jumpUrl='',$ajax=false){
        parent::success($message,$jumpUrl,true);
    }
    
    protected function error($message='',$jumpUrl='',$ajax=false) {
        parent::error($message,'',true);
    }
    
    protected function getFullUrl($url){
        $domain = $_SERVER['HTTP_HOST'];
        if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
            $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
            // '子域名'=>array('模块[/控制器]');
            foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
                $rule   =   is_array($rule)?$rule[0]:$rule;
                if(false === strpos($key,'*') && 0=== strpos($url,$rule)) {
                    $domain = $key.strstr($domain,'.'); // 生成对应子域名
                    $url    =  substr_replace($url,'',0,strlen($rule));
                    break;
                }
            }
        }
        $url   =  (is_ssl()?'https://':'http://').$domain.$url;
        return $url;
    }
}
